import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, setToken, removeToken } from './utils/auth'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/register'] // no redirect whitelist

function hasPermission(perms, permissions) {
  if (perms=='*') return true
  if (!permissions) return true
  return permissions.indexOf(perms)!=-1
}

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next()
      NProgress.done()
    } else {
      if (store.getters.perms == -1) {
        store.dispatch('GetInfo').then(res => {
          const perms = res.data.user.userType
          let menus = res.data.menus;
          // store.dispatch('GenerateRoutes', { menus, perms }).then(() => {
          store.dispatch('GenerateRoutes', { perms }).then(() => {
            router.addRoutes(store.getters.addRouters)
            next({ ...to, replace: true })
          })
        }).catch((err) => {
          next({ path: '/login' })
        })
      } else {
        // if (hasPermission(store.getters.perms, to.meta.perms)) {
        //   next()
        // } else {
        //   next({ path: '/401', replace: true, query: { noGoBack: true }})
        // }
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      console.log('直接进入')
      next()
    } else {
      next({ path: '/login' })
      console.log('重定向到登录页')
      // next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
